import {useState} from 'react';

function Square({value,lightFlag, onSquareClick}) {
    return (
        <button
            style={{backgroundColor: lightFlag ? 'green' : 'transparent'}}
            className="square"
            onClick={onSquareClick}>
            {value}
        </button>
    );
}

function Board({xIsNext, squares, onPlay}) {
    function handleClick(i) {
        if (calculateWinner(squares)[0] || squares[i]) {
            return;
        }
        const nextSquares = squares.slice();
        if (xIsNext) {
            nextSquares[i] = 'X';
        } else {
            nextSquares[i] = 'O';
        }
        nextSquares[9] = i //增加一列记录下标，可通过计算转坐标
        onPlay(nextSquares);
    }
    const [winner,winnerLine] = calculateWinner(squares);
    let status;
    if (winner) {
        status = '获胜的是: ' + winner;
    } else {
        if(!squares.includes(null)){
            status='实力伯仲之间，平局'
        }else {
            status = '下一步棋手: ' + (xIsNext ? 'X' : 'O');
        }
    }
    const numbers = [0, 1, 2]
    const listItems = numbers.map((number, rowIndex) => {
        return (
            <div className="board-row" key={rowIndex}>
                {
                    numbers.map((item, columnIndex) => {
                        let lightFlag=winnerLine.includes(rowIndex * 3 + columnIndex)
                        return renderSquare(rowIndex * 3 + columnIndex,lightFlag)
                    })
                }
            </div>
        )
    })
    //生成方格
    function renderSquare(i,lightFlag) {
        return (
            <Square
                key={i}
                value={squares[i]}
                lightFlag={lightFlag}
                onSquareClick={() => handleClick(i)}/>
        );
    }

    return (
        <>
            <div className="status">{status}</div>
            {listItems}
            {/*<div className="board-row">*/}
            {/*    <Square value={squares[0]} onSquareClick={() => handleClick(0)} />*/}
            {/*    <Square value={squares[1]} onSquareClick={() => handleClick(1)} />*/}
            {/*    <Square value={squares[2]} onSquareClick={() => handleClick(2)} />*/}
            {/*</div>*/}
            {/*<div className="board-row">*/}
            {/*    <Square value={squares[3]} onSquareClick={() => handleClick(3)} />*/}
            {/*    <Square value={squares[4]} onSquareClick={() => handleClick(4)} />*/}
            {/*    <Square value={squares[5]} onSquareClick={() => handleClick(5)} />*/}
            {/*</div>*/}
            {/*<div className="board-row">*/}
            {/*    <Square value={squares[6]} onSquareClick={() => handleClick(6)} />*/}
            {/*    <Square value={squares[7]} onSquareClick={() => handleClick(7)} />*/}
            {/*    <Square value={squares[8]} onSquareClick={() => handleClick(8)} />*/}
            {/*</div>*/}
        </>
    );
}

export default function Game() {
    const [history, setHistory] = useState([Array(10).fill(null)]);
    const [currentMove, setCurrentMove] = useState(0);
    const [sortReverseFlag,setSortReverseFlag]=useState(true); //排序标志
    const xIsNext = currentMove % 2 === 0;
    const currentSquares = history[currentMove];

    function handlePlay(nextSquares) {

        const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
        setHistory(nextHistory);
        setCurrentMove(nextHistory.length - 1);
    }

    function jumpTo(nextMove) {
        setCurrentMove(nextMove);
    }

    const moves = history.map((squares, move) => {
        let description;
        move=sortReverseFlag?move:history.length-move-1
        if (move > 0) {
            description = '跳到第' + move + '步，坐标('
                + Math.trunc(squares[9] / 3 + 1) + ',' + (squares[9] % 3 + 1) + ')'
            +"，下棋者："+ (move%2 ?'X':'O');
        } else {
            description = '重新开始游戏';
        }
        return (
            <li key={move}>
                <button
                    style={{fontWeight: (move === currentMove) ? 'bold' : 'normal'}}
                    onClick={() => jumpTo(move)}>
                    {description}
                </button>
            </li>
        );
    });
    return (
        <div className="game">
            <div className="game-board">
                <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay}/>
            </div>
            <div className="game-info">
                <button
                    onClick={() => setSortReverseFlag(!sortReverseFlag)}
                >
                    {sortReverseFlag ? '升序' : '降序'}
                </button>
                <ol>{moves}</ol>
            </div>

        </div>
    );
}

function calculateWinner(squares) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ];
    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return [squares[a],lines[i]];
        }
    }
    return [null,[]];
}
